package mblog.base.utils;

import freemarker.template.Template;
import mblog.base.lang.MtonsException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * Created by langhsu on 2017/11/13.
 */
@Component
public class MailHelper {
    private Logger log = Logger.getLogger(getClass());
    @Autowired
    private Environment env;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private JavaMailSender javaMailSender;

    @Async
    public void sendEmail(String template, String to, String title, Map<String, Object> content){
            // 配置发送邮件的环境属性
            final Properties props = new Properties();
            // 表示SMTP发送邮件，需要进行身份验证
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", env.getProperty("spring.mail.host"));
            // 如果使用ssl，则去掉使用25端口的配置，进行如下配置,
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", env.getProperty("spring.mail.port"));
            props.put("mail.smtp.port", env.getProperty("spring.mail.port"));
            // 发件人的账号
            props.put("mail.user", env.getProperty("spring.mail.username"));
            // 访问SMTP服务时需要提供的密码
            props.put("mail.password", env.getProperty("spring.mail.password"));
            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
//        mailSession.setDebug(true);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            try {
                String fromEmail = env.getProperty("spring.mail.username");
                // 设置发件人
                InternetAddress from = new InternetAddress(fromEmail);
                message.setFrom(from);
                // 设置收件人
                InternetAddress toEmail = new InternetAddress(to);
                message.setRecipient(MimeMessage.RecipientType.TO, toEmail);
                // 设置邮件标题
                message.setSubject(title,"text/html;charset=UTF-8");
                // 设置邮件的内容体
                message.setContent(render(template, content), "text/html;charset=UTF-8");
                // 发送邮件
                Transport.send(message);
            }
            catch (MessagingException e) {
                String err = e.getMessage();
                // 在这里处理message内容， 格式是固定的
                System.out.println(err);
            }
    }

//    public void sendEmail(String template, String to, String title, Map<String, Object> content) {
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//
//        try {
//
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
//            helper.setFrom(env.getProperty("spring.mail.username"));
//            helper.setTo(to);
//
//            helper.setSubject(title);
//            helper.setText(render(template, content), true);
//            javaMailSender.send(mimeMessage);
//
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            throw new  MtonsException("邮件发送失败", e);
//        }
//    }

    public String render(String templateName, Map<String, Object> model) {
        try {
            Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, "UTF-8");
            t.setOutputEncoding("UTF-8");
            return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
        } catch (Exception e) {
            throw new MtonsException(e.getMessage(), e);
        }
    }
}
